package cc.chinagps.gateway.client.codec;

import cc.chinagps.gateway.client.UnitClient;
import cc.chinagps.gateway.client.UnitClientManager;
import cc.chinagps.gateway.client.bean.DeviceInfo;
import cc.chinagps.gateway.client.packet.BasePacket;
import cc.chinagps.gateway.client.session.ISession;
import cc.chinagps.gateway.log.LogManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ClientMessageDecoder extends ByteToMessageDecoder {
    private static final int PACKET_MIN_LENGTH = 23;
    private UnitClient client;

    public ClientMessageDecoder(UnitClient client) {
        this.client = client;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        ISession session = client.getSession();
        if (session == null) {
            return;
        }
        if (in.readableBytes() < PACKET_MIN_LENGTH) {
            return;
        }

        session.setLastActiveTime(System.currentTimeMillis());
        DeviceInfo deviceInfo = client.getDeviceInfo();
        BasePacket packet = new BasePacket(deviceInfo);
        packet.decode(in);

        LogManager.t("{} recv packet info:{}", deviceInfo.getTerminalNo(), packet);

        out.add(packet);
    }
}
